<template>
    <div class="card-container">
        <el-card class="centered-card">
            <el-table :data="tableData" stripe :header-cell-style="{backgroundColor: 'aliceblue'}" @row-click="details">
                <el-table-column label="书名" prop="title" align="center"></el-table-column>
                <el-table-column label="作者" prop="author" align="center"></el-table-column>
                <el-table-column label="更新时间" prop="updateTime" align="center"></el-table-column>
            </el-table>
            <div class="block" style="margin: 10px 0">
                <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="pageNum"
                    :page-sizes="[5, 10, 15, 20]"
                    :page-size="pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total">
                </el-pagination>
            </div>
        </el-card>
    </div>
</template>

<script>
export default {
    props: {
        type: {
            type: String,
            required: true
        },
        fetchUrl: {
            type: String,
            required: true
        }
    },
    data() {
        return {
            tableData: [],
            pageNum: 1,
            pageSize: 10,
            total: 0,
        }
    },
    created() {
        this.load();
    },
    watch: {
        type() {
            this.pageNum = 1;  // 重置分页为第一页
            this.load();
        },
        fetchUrl() {
            this.pageNum = 1;  // 重置分页为第一页
            this.load();
        }
    },
    methods: {
        details(row, event, column) {
            this.$router.push({path: '/details', query: {row: JSON.stringify(row)}});
        },
        load() {
            this.$request.get(this.fetchUrl, {
                params: {
                    type: this.type,
                    page: this.pageNum,
                    size: this.pageSize
                }
            }).then(res => {
                this.tableData = res.content;
                this.total = res.totalElements;
            }).catch(error => {
                console.error('API request error:', error);
                this.tableData = []; // 或根据需求初始化数据
                this.total = 0;
            });
        },
        handleSelectionChange(selection) {
            console.log('Selection changed:', selection);
        },
        handleCurrentChange(pageNum) {
            this.pageNum = pageNum;
            this.load();
        },
        handleSizeChange(pageSize) {
            this.pageSize = pageSize;
            this.load();
        }
    }
}
</script>

<style scoped>
.card-container {
    display: flex;
    justify-content: center;
    text-align: center;
}

.centered-card {
    width: 50%;
    margin-top: 5%;
}
</style>